package com.ssfeng.youxia.dao.impl;

import com.ssfeng.youxia.entity.Sessions;
import com.ssfeng.youxia.service.ISessionsService;
import com.ssfeng.youxia.shiro.SessionUtils;
import com.ssfeng.youxia.shiro.ShiroUser;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.CachingSessionDAO;
import org.apache.shiro.session.mgt.eis.SessionIdGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import java.io.Serializable;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

@Repository("shiroSessionDao")
public class ShiroSessionDao extends CachingSessionDAO {

    private static final Logger logger = LoggerFactory.getLogger(ShiroSessionDao.class);

    @Autowired
    private ISessionsService sessionsService;

	@Override
	protected void doUpdate(Session session) {
		Sessions youxiaSessions = sessionsService.getById( session.getId());
		String sessionStr = SessionUtils.base64EncodeSession(session);
		youxiaSessions.setSession(sessionStr);
        Date date = session.getLastAccessTime();
        Instant instant = date.toInstant();
        ZoneId zoneId = ZoneId.systemDefault();
        LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime();
		youxiaSessions.setLastAccessTime(localDateTime);
		ShiroUser user = SessionUtils.getUserFromSession(session);
		if (!StringUtils.isEmpty(user)) {
			youxiaSessions.setUserId(user.getUserId());
		}
        sessionsService.updateById(youxiaSessions);
	}

	@Override
	protected void doDelete(Session session) {
        sessionsService.removeById (session.getId());
	}

	@Override
	protected Serializable doCreate(Session session) {
		SessionIdGenerator generator = this.getSessionIdGenerator();
		Serializable id = this.getSessionIdGenerator().generateId(session);
		this.assignSessionId(session, id);
		Sessions youxiaSessions = new Sessions();
		youxiaSessions.setStartTimesTamp(session.getStartTimestamp().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
		youxiaSessions.setLastAccessTime(session.getLastAccessTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
		youxiaSessions.setStatus(0);
		String sessionStr = SessionUtils.base64EncodeSession(session);
		youxiaSessions.setSession(sessionStr);
		youxiaSessions.setId(id.toString());
		ShiroUser user = SessionUtils.getUserFromSession(session);
		if (!StringUtils.isEmpty(user)) {
			youxiaSessions.setUserId(user.getUserId());
		}
        sessionsService.save(youxiaSessions);
		return id;
	}

	@Override
	protected Session doReadSession(Serializable sessionId) {
		Sessions youxiaSessions = sessionsService.getById(sessionId);
		if (StringUtils.isEmpty(youxiaSessions)) {
			return null;
		}
		return SessionUtils.base64DcodeSession(youxiaSessions.getSession());
	}


}
